/*
 * j4Win
 *  http://code.google.com/p/j4win/
 *
 * Copyright (C) 2006-2007 Felix Geyer, Moritz Laschinger
 *
 * This file is part of j4Win.
 *
 * j4Win is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * j4Win is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package j4win;

public class GameServer extends Game {
	public GameServer(GUI gui, PlayerType p1, PlayerType p2, KI[] ki) {
		super(gui, p1, p2, ki);
		isNetwork = (p2==PlayerType.NetworkClient);
		if (isNetwork) net = new NetworkServer(this, 4083);
	}
	
	public GameServer(GUI gui, PlayerType p1, PlayerType p2, KI[] ki, int port) {
		super(gui, p1, p2, ki);
		isNetwork = (p2==PlayerType.NetworkClient);
		if (isNetwork) net = new NetworkServer(this, port);
	}
	
	private boolean isNetwork;
	
	@Override
	protected void playerMove(int p, int col) {
		int row = field.add(col, p);
		if (isNetwork) {
			NetPacket packet = field.toPacket();
			packet.add(col);
			net.send(packet);
		}
		gui.playerMoved(field.clone(), col);
		
		if (field.hasPlayerWon(p, col, row)) {
			if (isNetwork) {
				if (p==1)
					net.send(new NetPacket(NetPacket.ID.OpponentWon));
				else
					net.send(new NetPacket(NetPacket.ID.YouWon));
			}
			gui.playerWon(p);
			endGame(isNetwork);
		}
		else if (field.isFull()) {
			if (isNetwork) {
				net.send(new NetPacket(NetPacket.ID.Tie));
			}
			gui.tie();
			endGame(isNetwork);
		}
		else {
			requestMove(p==1?2:1, col);
		}
	}

	@Override
	public void start() {
		if (isNetwork) {
			net.start();
		}
		else {
			gui.playerMoved(field, -1);
			requestMove(1, -1);
		}
	}
	
	@Override
	protected void requestMove(int player, int lastCol) {
		if (isNetwork) {
			if (player==1)
				net.send(new NetPacket(NetPacket.ID.OpponentTurn));
			else
				net.send(new NetPacket(NetPacket.ID.YourTurn));
		}
		gui.turnChanged(player);
		
		super.requestMove(player, lastCol);
	}

	public void packetReceived(NetPacket packet) {
		switch (packet.getID()) {
			case NetPacket.ID.Version:
				if ( packet.readInt() != Network.VERSION) {
					net.send(new NetPacket(NetPacket.ID.BadVersion));
				}
				else {
					NetPacket newPacket = field.toPacket();
					newPacket.add(-1);
					net.send(newPacket);
					gui.playerMoved(field, -1);
					requestMove(1, -1);
				}
				break;
			case NetPacket.ID.PlayerMove:
				playerMove(2, packet.readInt());
				break;
			default:
				System.err.println("GameServer: Unknown packet received");
		}
	}
}
